package clash

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/yysf-xin/dproxy/pkg/model"
)

type HTTPOptions struct {
	Method  string               `yaml:"method,omitempty" json:"method,omitempty"`
	Path    []string             `yaml:"path,omitempty" json:"path,omitempty"`
	Headers map[string]*[]string `yaml:"headers,omitempty" json:"headers,omitempty"`
}

func (j *HTTPOptions) GormDataType() string {
	return "text"
}

func (j *HTTPOptions) Scan(value interface{}) (err error) {
	switch value.(type) {
	case []byte:
		*j = HTTPOptions{}
		err = json.Unmarshal(value.([]byte), j)
	case string:
		err = json.Unmarshal([]byte(value.(string)), j)
	default:
		err = errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}

	return err
}

func (j *HTTPOptions) Value() (driver.Value, error) {
	if j == nil {
		return nil, nil
	}
	return json.Marshal(j)
}

type ConfigClash struct {
	model.Proxy `yaml:",inline"`
	Name        string `yaml:"name" gorm:"size:128"`
	Type        string `yaml:"type" gorm:"size:32"`

	Password string `json:",omitempty" yaml:"password" gorm:"size:128"`
	Cipher   string `json:",omitempty" yaml:"cipher" gorm:"size:48"`
	UDP      bool   `json:",omitempty" yaml:"udp"`
	TLS      bool   `json:",omitempty" yaml:"tls"`

	UUID    string `json:",omitempty" yaml:"uuid" gorm:"size:48"`
	AlterId int    `json:",omitempty" yaml:"alterId"`
	Network string `json:",omitempty" yaml:"network" gorm:"size:32"`

	WsPath     string       `json:",omitempty" yaml:"ws-path" gorm:"size:128"`
	ServerName string       `json:",omitempty" yaml:"servername" gorm:"size:128"`
	WsHeaders  model.SSJson `json:",omitempty" yaml:"ws-headers" gorm:"size:256"`
	HttpOpts   *HTTPOptions `json:",omitempty" yaml:"http-opts" gorm:"size:256"`
	H2Opts     model.SSJson `json:",omitempty" yaml:"h2-opts" gorm:"size:256"`
}

//type ConfigClashFail ConfigClash
//func (c *ConfigClashFail) TableName() string {
//	return "proxy_clash_fail"
//}

func (c *ConfigClash) TableName() string {
	return "proxy_clash"
}

type UrlVal struct {
	Url      string `yaml:"url,omitempty"`
	Interval int    `yaml:"interval,omitempty"`
}
type Provider struct {
	Type   string `yaml:"type,omitempty"`
	Path   string `yaml:"path,omitempty"`
	UrlVal `yaml:",inline"`
}
type HealthCheck struct {
	Enable bool `yaml:"enable"`
	UrlVal `yaml:",inline"`
}
type Group struct {
	Name    string   `yaml:"name"`
	Type    string   `yaml:"type"`
	Proxies []string `yaml:"proxies,omitempty"`
	Use     []string `yaml:"use,omitempty"`
	UrlVal  `yaml:",inline"`
}
type RootClash struct {
	Proxies       []*ConfigClash       `yaml:"proxies,omitempty"`
	ProxyGroup    []*Group             `yaml:"proxy-groups,omitempty"`
	ProxyProvider map[string]*Provider `yaml:"proxy-providers,omitempty"`
	Rules         []string             `yaml:"rules,omitempty"`
}
